package com.cbgolf.oa.views;

import android.app.Activity;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.TeeTimeAdapter;
import com.cbgolf.oa.adapter.TeeTimeAdapter.ITeetimeAdapterWaiter;
import com.cbgolf.oa.adapter.recycle.CommonAdapter;
import com.cbgolf.oa.adapter.recycle.ViewHolder;
import com.cbgolf.oa.base.BaseViewNew;
import com.cbgolf.oa.contract.ITeetimeContract;
import com.cbgolf.oa.entity.TeeTimeBean;
import com.cbgolf.oa.entity.TeeTimeBean.TeeTimesBean;
import com.cbgolf.oa.event.Events;
import com.cbgolf.oa.manager.DataManager;
import com.cbgolf.oa.manager.DialogManager;
import com.cbgolf.oa.manager.PopManager;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.util.ErrorUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.TypeUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xutils.view.annotation.ViewInject;

/**
 * Created by lq on 2018/1/5.
 */
public class TeetimeViewImp extends BaseViewNew implements ITeetimeContract.IView,
    OnRefreshListener, ITeetimeAdapterWaiter {

  @ViewInject(R.id.topLayout_rl)
  private View topLayout;
  @ViewInject(R.id.topBack_ll)
  private View topBack;
  @ViewInject(R.id.title_tv)
  private TextView titleTv;
  @ViewInject(R.id.title_iv)
  private ImageView titleIv;
  @ViewInject(R.id.title_ll)
  private View titleView;
  @ViewInject(R.id.topRight_tv)
  private TextView topRightTv;
  //
  @ViewInject(R.id.refreshView)
  private SmartRefreshLayout refreshLayout;
  @ViewInject(R.id.recycleView)
  private RecyclerView recyclerView;
  //
  @ViewInject(R.id.calendar_recycleview)
  private RecyclerView calendarRecy;
  @ViewInject(R.id.calendar_ll)
  private View calendar;


  private TeeTimeAdapter adapter;
  private List<TeeTimesBean> listData = new ArrayList<>();
  private CommonAdapter<TeeTimeBean> calenAdapter;
  private Map<Integer, Boolean> calendarState = new HashMap<>();
  private List<TeeTimeBean> listCalendar = new ArrayList<>();
  private List<String> listCode = new ArrayList<>();
  private ErrorView errorView;
//  private PopupWindow pop;

  private String codeType;
  private ITeetimeContract.Waiter worker;

  public TeetimeViewImp(Activity act, ITeetimeContract.Waiter worker) {
    this.worker = worker;
    ViewUtils.autoInjectAllField(this, act);
    super.init(act);
  }


  @Override
  protected void setViews() {
    errorView = new ErrorView(context);
    ViewUtils.setText(titleTv, worker.getActivityTitle());
    ViewUtils.setText(topRightTv, context.getString(R.string.close_park));
    ViewUtils.setVisible(topRightTv, DataUtil.hasClosePermission());
    setListAdapter();
    ViewUtils.setRefreshCircleHeader(context, refreshLayout);
    refreshLayout.setEnableLoadmore(false);
    selectTime = System.currentTimeMillis();
  }

  @Override
  protected void setListener() {
    super.setListener();
    refreshLayout.setOnRefreshListener(this);
    topBack.setOnClickListener(v -> worker.back());
    calendar.setOnClickListener(
        v -> DialogManager.getInstance().showCalendarDialog(context, selectTime));
    titleView.setOnClickListener(v -> {
      if (Util.listIsNull(listCode) || listCode.size() == 1) {
        return;
      }
      PopManager.getInstance().showTeetimeABPop(context, listCode, codeType, topLayout,
          (id, name, position) -> {
            ViewUtils.setText(titleTv, name);
            ViewUtils.setImage(titleIv, R.mipmap.teetime_arrowup);
            codeType = id;
            requestTeetime(0, codeType);
          });
    });
    ViewUtils.setClick(topRightTv, v -> worker.showCloseParkList());
  }

  private void setListAdapter() {
    adapter = new TeeTimeAdapter(context, this);
    getCalendarData();
    setCalendarAdapter();
    GridLayoutManager gm = new GridLayoutManager(context, 2);
    recyclerView.setLayoutManager(gm);
    recyclerView.setHasFixedSize(true);
    recyclerView.setAdapter(adapter);

  }


  private void getCalendarData() {
    listCalendar.clear();
    TeeTimeBean bean;
    if (selectTime <= 0) {
      selectTime = System.currentTimeMillis();
    }
    long everyDay;
    for (int i = 0; i < DateUtil.DAYS_OF_WEEK; i++) {
      calendarState.put(i, i == DateUtil.DAYS_OF_WEEK / 2);
      everyDay = selectTime + (i - DateUtil.DAYS_OF_WEEK / 2) * DateUtil.getOneDay();
      bean = new TeeTimeBean();

      bean.day = String.valueOf(DateUtil.getDay(new Date(everyDay)));
      bean.start = String.valueOf(DateUtil.getDayBegin(everyDay));
      bean.end = String.valueOf(DateUtil.getDayEnd(everyDay));
      bean.week = DateUtil.getWeek(everyDay);
      listCalendar.add(bean);
    }
  }

  private void setCalendarAdapter() {

    calenAdapter = new CommonAdapter<TeeTimeBean>(context, R.layout.item_teetime_calendar,
        listCalendar) {
      @Override
      protected void convert(ViewHolder holder, TeeTimeBean bean, int position) {
        if (null == bean) {
          return;
        }
        holder.setText(R.id.week_tv, TextUtil.Text(bean.week));
        holder.setText(R.id.day_tv, TextUtil.Text(bean.day));
        holder.setBackgroundColor(R.id.layout, ContextCompat.getColor(context,
            DataUtil.getMapBoolean(calendarState, position) ?
                R.color.bg_blue_login : R.color.bg_blue_calendar));
        holder.setTextColor(R.id.week_tv, ContextCompat.getColor(context,
            DataUtil.getMapBoolean(calendarState, position) ?
                R.color.white : R.color.text_blue));
        holder.setOnClickListener(R.id.layout, v -> {
          if (DataUtil.getMapBoolean(calendarState, position)) {
            return;
          }
          for (int i = 0; i < calendarState.size(); i++) {
            calendarState.put(i, (i == position));
          }
          requestTeetime(TypeUtil.parseLong(bean.start), codeType);
          notifyDataSetChanged();
        });
      }
    };
    GridLayoutManager gm = new GridLayoutManager(context, 7);
    calendarRecy.setLayoutManager(gm);
    calendarRecy.setHasFixedSize(true);
    calendarRecy.setAdapter(calenAdapter);
  }

  private long selectTime = System.currentTimeMillis();

  private void requestTeetime(long time, String codeType) {
    if (0 == time) {
      selectTime = TypeUtil.zeroLong(time, System.currentTimeMillis());
      worker.requestTeetime(0, codeType);
      return;
    }
    if (time > (DateUtil.getDayEndTime(selectTime).getTime() + 3 * DateUtil.getOneDay())
        || DateUtil.getDayEndTime(time).getTime()
        < (DateUtil.getDayEndTime(selectTime).getTime() - 3 * DateUtil.getOneDay())) {
      selectTime = time;
      getCalendarData();
    } else {
      for (int i = 0; i < listCalendar.size(); i++) {
        calendarState.put(i, DateUtil.getDay(time) == DateUtil.getDay(listCalendar.get(i).start));
      }
    }
    calenAdapter.notifyDataSetChanged();
    worker.requestTeetime(time, codeType);
  }

  @Override
  public void showProgress() {
    if (null != refreshLayout && refreshLayout.isRefreshing()) {
      return;
    }
    AnimaUtil.showLoading(context, false);
  }

  @Override
  public void stopProgress() {
    if (null != refreshLayout) {
      refreshLayout.finishRefresh();
    }
    AnimaUtil.stopLoading();
  }

  @Override
  public void requestFail(String msg, int code) {
    if (null != errorView) {
      errorView.showError(refreshLayout, TextUtil.Text(msg, ErrorUtil.NODATA),
          code, null);
    }
  }

  @Override
  public void requestOver(Events event) {
    if (null == event) {
      return;
    }
    switch (event.msgTarget) {
      case DataManager.TEETIME_DATA:
        stopProgress();
        if (Util.listIsNull(event.listTeetime)) {
          requestFail(event.errorMsg, event.errorCode);
          return;
        }
        listData.clear();
        listData.addAll(event.listTeetime);
        errorView.showData(refreshLayout);
        adapter.setData(listData);
        adapter.notifyDataSetChanged();
        break;
      case DataManager.TEETIME_AB_CODE:
        if (Util.listIsNull(event.listString)) {
          requestFail(event.errorMsg, event.errorCode);
        } else {
          listCode.clear();
          listCode.addAll(event.listString);
          codeType = listCode.get(0);
          ViewUtils.setText(titleTv, Util.isNull(codeType) ?
              worker.getActivityTitle()
              : new StringBuffer()
                  .append("Teetime-")
                  .append(codeType.substring(0, 1))
                  .append("半场"));
          ViewUtils.setVisible(titleIv, true);
          ViewUtils.setImage(titleIv, R.mipmap.teetime_arrowup);
        }
        break;
      case DataManager.TEETIME_CALENDAR_CHOICE:
        DialogManager.getInstance().release();
        requestTeetime(event.selectTime, codeType);
        break;
      case DataManager.TEETIME_ADD_REDUCE_FAIL:
        Util.show(event.errorMsg);
        break;
      default:
        break;
    }

  }

  @Override
  public void onRefresh(RefreshLayout refreshlayout) {
    worker.refresh();
  }


  @Override
  public void addPerson(TeeTimesBean bean) {
    worker.addPerson(bean);
  }

  @Override
  public void reducePerson(TeeTimesBean bean) {
    worker.reducePerson(bean);
  }
}

